package ldh.maker.db;

import ldh.database.Column;
import ldh.database.Table;
import ldh.maker.util.DbUtil;
import ldh.maker.util.MakerConfig;
import ldh.maker.util.UiUtil;
import ldh.maker.vo.TreeNode;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by ldh on 2017/4/4.
 */
public class PojoFunctionDb {

    public static void loadData(TreeNode treeNode, Table table) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "select * from pojo_function where tree_node_id = ? and pojo_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, treeNode.getId());
        statement.setInt(2, table.getId());
        ResultSet rs = statement.executeQuery();
        Map<String, Boolean> map = new TreeMap<>();
        while(rs.next()){
            map.put(rs.getString("name"), rs.getBoolean("is_create"));
        }
        MakerConfig.getInstance().addFunctionMap(table.getName(), map);
        statement.close();
    }

    public static void saveData(int treeNodeId, Table table) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "insert into pojo_function(name, is_create, pojo_id, tree_node_id) values(?, ?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        Map<String, Boolean> functions = MakerConfig.getInstance().getFunctionMap(table.getName());
        for (Map.Entry<String, Boolean> entry : functions.entrySet()) {
            statement.setString(1, entry.getKey());
            statement.setBoolean(2, entry.getValue());
            statement.setInt(3, table.getId());
            statement.setInt(4, treeNodeId);
            statement.addBatch();
        }
        statement.executeBatch();
        statement.close();
    }

    public static void deleteData(int treeNodeId, Table table) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "delete from pojo_function where tree_node_id = ? and pojo_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, treeNodeId);
        statement.setInt(2, table.getId());
        statement.executeUpdate();
        statement.close();
    }

    public static void deleteData(int treeNodeId) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "delete from pojo_function where tree_node_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, treeNodeId);
        statement.executeUpdate();
        statement.close();
    }

}
